package com.zee.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zee.admin.dao.SysRoleDataScopeDao;
import com.zee.admin.entity.SysRoleDataScope;
import com.zee.admin.service.ISysRoleDataScopeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysRoleDataScopeServiceImpl extends ServiceImpl<SysRoleDataScopeDao, SysRoleDataScope>
        implements ISysRoleDataScopeService {

    @Override
    public List<Integer> getDeptIdList(Integer roleId) {
        return baseMapper.getDeptIdList(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Integer roleId, List<Integer> deptIdList) {
        //先删除角色数据权限关系
        deleteByRoleIds(new Integer[]{roleId});

        //角色没有一个数据权限的情况
        if (CollUtil.isEmpty(deptIdList)) {
            return;
        }

        //保存角色数据权限关系
        for (Integer deptId : deptIdList) {
            SysRoleDataScope sysRoleDataScope = new SysRoleDataScope();
            sysRoleDataScope.setDeptId(deptId);
            sysRoleDataScope.setRoleId(roleId);

            //保存
            this.save(sysRoleDataScope);
        }
    }

    @Override
    public void deleteByRoleIds(Integer[] roleIds) {
        baseMapper.deleteByRoleIds(roleIds);
    }
}